package game

import (
	"message"
	"message/netlib"
	"github.com/name5566/leaf/log"
)

// 消息处理 c2s

func init() {
	Register(message.MSG_USER_INFO, handleUserInfo)
	Register(message.MSG_LOGOUT, handleLogout)
	Register(message.MSG_GET_ROOM_INFO, handleGetRoomInfo)
	Register(message.MSG_GET_HALL_LIST, handleGetHallList)
	Register(message.MSG_CHAT, handleChatMsg)
	Register(message.MSG_START_GAME, handleStartGame)
	Register(message.MSG_STOP_GAME, handleStopGame)
	Register(message.MSG_ENTER_ROOM, handleEnterRoom)
	Register(message.MSG_CHANGE_ROOM, handleChangeRoom)
	Register(message.MSG_SITDOWN, handleSitDown)
	Register(message.MSG_STANDUP, handleStandUp)
	Register(message.MSG_ACTION, handleAction)
	Register(message.MSG_SHOW_CARD, handleShowCard)
}


// 玩家登出游戏
func handleLogout(args []interface{}) {
	log.Debug("handleLogout")
	user := GetUserByAgent(args[1])
	if user != nil {
		user.logout()
	} else {
		log.Error("handleLogout 玩家不存在: %v", user)
		PrintUsersOnline()
	}
}

func handleUserInfo(args []interface{}) {
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqUserInfo()
	}
}

func handleGetRoomInfo(args []interface{}) {
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqGetRoomInfo()
	}
}

func handleGetHallList(args []interface{}) {
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqGetHallList()
	}
}

func handleChatMsg(args []interface{}) {
	msg := netlib.Deserialize(args[0], message.C2S_Chat{}).(*message.C2S_Chat)
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqChat(msg.GetMessage(), int(msg.GetTarget()))
	}
}

func handleStartGame(args []interface{}) {
	msg := netlib.Deserialize(args[0], message.DataInt{}).(*message.DataInt)
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqStartGame(int(msg.GetParam()))
	}
}

func handleStopGame(args []interface{}) {
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqStopGame()
	}
}

func handleEnterRoom(args []interface{}) {
	msg := netlib.Deserialize(args[0], message.DataInt{}).(*message.DataInt)
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqEnterRoom(int(msg.GetParam()))
	}
}

func handleChangeRoom(args []interface{}) {
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqChangeRoom()
	}
}

func handleSitDown(args []interface{}) {
	msg := netlib.Deserialize(args[0], message.DataInt{}).(*message.DataInt)
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqSitDown(int(msg.GetParam()))
	}
}

func handleStandUp(args []interface{}) {
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqStandUp()
	}
}



// 处理玩家的操作
func handleAction(args []interface{}) {
	log.Debug("handleAction")
	msg := netlib.Deserialize(args[0], message.C2S_Action{}).(*message.C2S_Action)
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqAction(msg.GetAction(), int(msg.GetParam()))
	}
}

func handleShowCard(args []interface{}) {
	user := GetUserByAgent(args[1])
	if user != nil {
		user.reqShowCard()
	}
}
